import json

#1.字符串 和 dic list 转换

#字符串-->dic list
data='[{"name":"张三","age":20},{"name":"李四","age":18}]'#最外层有且仅有一个
list_data=json.loads(data)
print(data,type(data))
print(list_data,type(list_data))

#dict list -->字符串
list2=[{"name":"张三","age":20},{"name":"李四","age":18}]
data_json=json.dumps(list2)
print(data_json,type(data_json))#[{"name": "\u5f20\u4e09", "age": 20}, {"name": "\u674e\u56db", "age": 18}] <class 'str'>
#dict list写入文件
with open('数据.json','w') as f:
    #f.write(list2)#TypeError: a bytes-like object is required, not 'list'
    f.write(data_json)
#2.文件对象 和 dict list 转换
#fp 是 file path
fp=open('数据new.json','w')
json.dump(list2,fp)
fp.close()
#读取文件---list dict
fp=open('数据new.json','r')
result=json.load(fp)
print(result)
fp.close()